<?php

class Settings extends CActiveRecord {

    public $upload_dir;
    public $image;

    public function init() {
        $this->upload_dir = dirname(Yii::app()->basePath) . DIRECTORY_SEPARATOR . 'upload';
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

//    public function getValbyKey($key){
//        return $this->findByAttributes(array('key'=>':key'),array(':key'=>$key));
//    }

    public function getResourceName() {
        return 'Settings';
    }

    public function tableName() {
        return '{{Settings}}';
    }

    public function rules() {
        return array(
            array('key', 'unique'),
            array('key', 'required'),
//			array('isnumber', 'numerical', 'integerOnly'=>true),
            array(
                'key', 'match', 'not' => true, 'pattern' => '/[^a-zA-Z0-9_-]/',
                'message' => 'Chỉ được sử dụng các ký tự a-z, A-Z, 0-9 và dấu gạch chân ( _ ), gạch ngang ( - )', 'on' => 'update, create'
            ),
            array('key', 'length', 'max' => 255),
            array('value, isnumber', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, key, value, isnumber', 'safe', 'on' => 'search'),
        );
    }

    public function relations() {
        return array(
        );
    }

    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'key' => 'Tên',
            'value' => 'Nội dung',
//			'isnumber' => 'Nội dung là số',
        );
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            $this->value = serialize($this->value);
            return true;
        }
        return false;
    }

    protected function afterSave() {
        Controller::settingSet($this->key, unserialize($this->value), 'system');
        return parent::afterSave();
    }

    protected function beforeDelete() {
        if (parent::beforeDelete()) {
            Controller::settingDelete();
            return true;
        }
        else
            return false;
    }

    public function getUrlPhoto() {
        $v = Settings::model()->findByAttributes(array('key' => $this->key));
        return Yii::app()->baseUrl . '/upload/' . $this->key . '_' . unserialize($v->value);
    }

    public function search() {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('`key`', $this->key, true);

        //$criteria->compare('value',$this->value,true);
        if ($this->value)
            $criteria->addCondition("MATCH (value) AGAINST ('{$this->value}' IN BOOLEAN MODE)");

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

}